﻿namespace Snake
{
    public class TimeWaiting
    {
        /// <summary>
        /// 等待时间
        /// </summary>
        public float WaitTime { get; private set; }

        /// <summary>
        /// 目标时间
        /// </summary>
        public float TargetTime { get; private set; }

        /// <summary>
        /// 时间节点
        /// </summary>
        public string TimeNode { get; private set; } = "root";

        /// <summary>
        /// 开始时间
        /// </summary>
        public float StartTime { get; private set; }

        /// <summary>
        /// 时间计算模式
        /// </summary>

        public bool UnscaleMode { get; private set; }

        /// <summary>
        /// 已经过去时间
        /// </summary>
        public float ElapseTime => Now - StartTime;

        /// <summary>
        /// 已经等待百分比
        /// </summary>

        public float Percent => ElapseTime / WaitTime;

        /// <summary>
        /// 超时
        /// </summary>
        public bool IsTimeOut => Now >= TargetTime;

        private float Now => UnscaleMode
            ? App.Instance.GetTimeScalingContext(TimeNode).ElapseUnscaleTime
            : App.Instance.GetTimeScalingContext(TimeNode).ElapseTime;

        public TimeWaiting(float waitSec, bool unscaleMode = false)
        {
            UnscaleMode = unscaleMode;
            Restart(waitSec);
        }

        public TimeWaiting(string node, float waitSec, bool unscaleMode = false)
        {
            TimeNode = node;
            UnscaleMode = unscaleMode;
            Restart(waitSec);
        }

        /// <summary>
        /// 直接设置超时
        /// </summary>
        public void SetTimeOut()
        {
            TargetTime = StartTime;
            StartTime -= WaitTime;
        }

        public void Restart()
        {
            StartTime = Now;
            TargetTime = Now + WaitTime;
        }

        public void Restart(float waitSec)
        {
            WaitTime = waitSec;
            Restart();
        }
    }
}